using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Globalization;

namespace Camalon.Drawing
{
	public class ShearConverter:ExpandableInstanceConverter
	{
		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			if ( value is string ) 
			{
				string sVal = (string)value;
				sVal = sVal.Trim();
				if( sVal.Length == 0) return Shear.Empty;
				if( sVal.ToLower().IndexOf("empty") != -1) return Shear.Empty;

				string[] args = sVal.Split(';');
				
				if( args.Length == 2 || args[3] != bool.TrueString )
					return new Shear( int.Parse( args[0]),int.Parse( args[1]));
				else
					return new Shear( int.Parse( args[0]),int.Parse( args[1]), bool.Parse(args[3]));
			}

			return base.ConvertFrom (context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if( value is Shear)
			{
				Shear m = (Shear) value;

				if (destinationType == typeof(string)) 
				{
					if( m.IsEmpty) return "Empty";
					return String.Format( "{0}; {1}; {2}", m.X,m.Y, m.AppendRotate);
				}

				if (destinationType == typeof(InstanceDescriptor) && value is Shear) 
				{
					if( !m.AppendRotate )
					{
						ConstructorInfo ctor = typeof(Shear).GetConstructor(new Type[] {typeof(int), typeof(int)});
						if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.X,m.Y});
					}
					else
					{
						ConstructorInfo ctor = typeof(Shear).GetConstructor(new Type[] {typeof(int), typeof(int), typeof(bool)});
						if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.X,m.Y,m.AppendRotate});
					}
				}

			}

			return base.ConvertTo (context, culture, value, destinationType);
		}


	}

}
